const router = require('koa-router')()
const query = require("../db/mysql");
const fs = require("fs");
const path = require("path");

router.get('/adminauthor', async (ctx, next) => {
    try {
        let sql = `SELECT aId,aName FROM author`
        let data = await query(sql);
        return ctx.body = {
            status: 200,
            data: data,
            msg: ''
        }
    } catch (error) {
        console.log(error);
        return ctx.body = {
            status: 500,
            msg: error
        }
    }
})

router.get('/oneauthor', async (ctx, next) => {
    const aId = ctx.query.aId
    try {
        let sql = `SELECT aId,aName,aInformation FROM author WHERE aId = ?`
        let data = await query(sql,[aId]);
        return ctx.body = {
            status: 200,
            data: data,
            msg: ''
        }
    } catch (error) {
        console.log(error);
        return ctx.body = {
            status: 500,
            msg: error
        }
    }
})

router.post('/adminauthor', async (ctx, next) => {
    const {'作者id: ':aId, '作者姓名: ':aName,'作者信息: ': aInformation} = ctx.request.body;
    try {
        let sql = `insert into author values(?,?,?)`;
        let data = await query(sql,[aId,aName,aInformation]);
        return ctx.body = {
            status: 200,
            data: '上传成功！',
            msg: ''
        }
    } catch (error) {
        console.log(error);
        return ctx.body = {
            status: 500,
            msg: error
        }
    }
})

router.post('/udauthor',async (ctx,next)=>{
    try{
        // 
        const {'作者id: ':aId,'作者姓名: ':aName,'作者信息: ':aInformation} = ctx.request.body
        let sql = 'UPDATE author SET aId=?,aName=?,aInformation=? WHERE aId = ?'
        await query(sql,[aId,aName,aInformation,aId])
        return ctx.body = {
            status:200,
            msg:'update success'
        }
    }catch{err=>{
        console.log(err)
        return ctx.body = {
            status:500,
            msg:err
        }
    }}
})

router.delete('/adminauthor',async(ctx,next)=>{
    try {
        let sql = `delete from author where aId = ?`;
        let data = await query(sql, [ctx.query.aId]);
        return ctx.body = 'success'
      } catch (error) {
        console.log(error);
        return ctx.body = {
          status: 500,
          msg: error
        }
      }

})

module.exports = router;